package com.decade.qiyeshapan.controller;

import com.decade.qiyeshapan.entity.User;
import com.decade.qiyeshapan.service.MessageService;
import com.decade.qiyeshapan.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/api/messages")
public class MessageController {

    @Autowired
    private MessageService messageService;
    
    @Autowired
    private UserService userService;

    /**
     * 发送游戏开始通知给指定游戏的所有用户
     */
    @PostMapping("/game-start")
    public void notifyGameStart(@RequestBody Map<String, String> request) throws IOException {
        String gameId = request.get("gameId");
        String message = "{\"type\":\"gameEvent\", \"content\":\"游戏已开始！\"}";
        
        // 获取游戏内所有用户
        Map<String, User> users = userService.getAllUsers(gameId);
        
        // 遍历发送消息
        for (User user : users.values()) {
            if (user.getSocketId() != null && !user.getSocketId().isEmpty()) {
                messageService.sendToUser(user.getSocketId(), message);
            }
        }
    }

    /**
     * 发送自定义消息给指定用户
     */
    @PostMapping("/send-to-user")
    public void sendToUser(@RequestBody Map<String, String> request) throws IOException {
        String socketId = request.get("socketId");
        String content = request.get("content");
        String message = String.format("{\"type\":\"custom\", \"content\":\"%s\"}", content);
        messageService.sendToUser(socketId, message);
    }
} 